package com.atguigu.springcloud.controller;

import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import com.atguigu.springcloud.service.PaymentSerivce;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RequestMapping(value = "/payment")
@RestController
@Slf4j
public class PaymentController {
    @Autowired
    private PaymentSerivce paymentSerivce;

    @Value("${server.port}")
    private String serverPort;

    @Resource
    private DiscoveryClient discoveryClient;

    @RequestMapping(value = "/creat")
    public CommonResult creatPayment(Payment payment) {
        // CommonResult commonResult = new CommonResult();
        int creat = paymentSerivce.creat(payment);
        log.info("*********传入参数" + payment);

        if (creat > 0) {
            return new CommonResult(200, "插入数据库成功,serverPort: " + serverPort, creat);
        } else {
            return new CommonResult(444, "插入数据库成功,serverPort: " + serverPort, creat);
        }

    }

    @RequestMapping(value = "/get/{id}")
    public CommonResult get(@PathVariable("id") Long id) {
        Payment payment = paymentSerivce.getPaymentById(id);
        //return new CommonResult(200,"查询成功,serverPort:  "+serverPort,payment);s
        return new CommonResult(200, "查询成功:ServerPort:" + serverPort, payment);
    }

    @ResponseBody
    @GetMapping(value = "/payment/discovery")
    public Object discovery() {
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            System.out.println(service);
        }
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances) {
            instance.getHost();
            instance.getInstanceId();
            instance.getPort();
            instance.getServiceId();
        }
        return services;
    }

    @RequestMapping(value = "/feign/timeout")
    public String paymentFeignTimeOut() {
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return serverPort;
    }

    @GetMapping("/lb")
    public String getPaymentLb(){
           return serverPort;
    }
    @GetMapping("/payment/zipkin")
    public String paymentZipkin()
    {
        return "hi ,i'am paymentzipkin server fall back，welcome to atguigu，O(∩_∩)O哈哈~";
    }

}
